<template>
  <el-card class="box">
    <div class="top">
        <span style="font-size: 25px; color: #203857; margin-right: 10px;">公告管理</span>
        <el-button type="primary" @click="openCreateDialog">新建公告</el-button>
        <el-button type="danger" @click="deleteSelectedAnnouncements">删除选中公告</el-button>
    </div>

    <el-table :data="announcements" @selection-change="handleSelectionChange">
      <!-- 表格列定义 -->
       <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号" width="55" align="center"></el-table-column>
      <el-table-column prop="title" label="标题" align="center"></el-table-column>
      <el-table-column prop="author" label="发布人" align="center"></el-table-column>
      <el-table-column prop="createTime" label="发布时间" align="center"></el-table-column>
      <el-table-column prop="deadLine" label="截止时间" align="center"></el-table-column>
      <el-table-column label="操作" align="center" width="250">
        <template #default="{ row }">
          <div class="button-group">
            <el-button type="primary" size="small" @click="showDetails(row)">详情</el-button>
            <el-button type="success" size="small" :disabled="isFileCountPassed(row.fileCount)" @click="showAttachments(row.id, row.title)">查看附件</el-button>
        </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="pageSize"
      :page-sizes="[3, 5, 7, 9]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
  </el-card>

  <!-- 创建预览对话框 -->
<el-dialog v-model="dialogVisible" width="800" :before-close="handleClose">
    <template #header="{}">
        <div class="my-header">
        <span class="titleClass">PDF 预览</span>
        </div>
    </template>
    <div class="details">
        <div v-if="selectedAnnouncement.noticeFileUrl">
        <iframe
            :src="`${selectedAnnouncement.noticeFileUrl}#toolbar=0&navpanes=0&scrollbar=0`"
            width="100%"
            height="600px"
            frameborder="0"
        ></iframe>
        </div>
    </div>
    <template #footer>
        <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        </div>
    </template>
</el-dialog>

<!-- 查看附件对话框 -->
<AttachmentList ref="attachmentList" />

  <!-- 创建公告对话框 -->
 <el-dialog v-model="createDialogVisible" title="新建公告" width="50%">
    <el-form :model="newAnnouncement" :rules="rules">
      <el-form-item label="标题">
        <el-input style = "width:50%"  v-model="newAnnouncement.title"></el-input>
      </el-form-item>
      <el-form-item label="截止时间">
        <el-date-picker v-model="newAnnouncement.deadLine" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"  :disabled-date="disabledDate" ></el-date-picker>
      </el-form-item>
      <el-form-item label="通知文件">
        <el-upload
          action=""
          :auto-upload="false"
          accept=".pdf"
          :on-change="handleNoticeFileChange"
          :file-list="noticeFileList"
          :limit="1"
          list-type="text"
        >
          <el-button slot="trigger" size="small" type="primary">选取通知文件</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="附件文件">
        <el-upload
          action=""
          :auto-upload="false"
          :on-change="handleAttachmentFileChange"
          :file-list="attachmentFileList"
          :multiple="true"
          :limit="5"
          list-type="text"
        >
          <el-button slot="trigger" size="small" type="primary">选取附件文件</el-button>
        </el-upload>
      </el-form-item>
       <el-form-item label="上传进度">
      </el-form-item>
      <el-progress type="line" :text-inside="true" :stroke-width="26" :percentage="uploadProgress" :status="progressStatus"></el-progress>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="createDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAnnouncement">发 布</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { ElCard, ElTable, ElTableColumn, ElButton, ElDialog, ElForm, ElFormItem, ElInput, ElDatePicker, ElMessage, ElPagination, ElProgress} from 'element-plus';
import { fetchAnnouncements, issueNotice ,deleteAnnouncementsApi} from '@/api/announcement';
import AttachmentList from '@/components/Notice/AttachmentList.vue';

const announcements = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const dialogVisible = ref(false);
const selectedAnnouncements = ref([]);
const selectedAnnouncement = ref({});
const attachmentList = ref(null);

// 新建公告相关
const createDialogVisible = ref(false);
const newAnnouncement = ref({
  title: '',
  deadLine: '',
  noticeFile: null,
  attachmentFiles: []
});
const noticeFileList = ref([]);
const attachmentFileList = ref([]);
const uploadProgress = ref(0);
const progressStatus = ref(null);

// 验证规则
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  deadLine: [{ required: true, message: '请选择截止时间', trigger: 'change' }]
};

// 禁用早于当前时间的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 86400000; // 禁用今天之前的日期
};

const handleSelectionChange = (val) => {
  selectedAnnouncements.value = val.map(item => item.id);
};

const openCreateDialog = () => {
    createDialogVisible.value = true;
    newAnnouncement.value = {
        title: '',
        deadLine: '',
        noticeFile: null,
        attachmentFiles: []
    };
    noticeFileList.value = [];
    attachmentFileList.value = [];
    uploadProgress.value = 0;
    progressStatus.value = null;
};
const handleNoticeFileChange = (file) => {
    newAnnouncement.value.noticeFile = file.raw;
    noticeFileList.value = [file];
};


const handleAttachmentFileChange = (file, fileList) => {
    newAnnouncement.value.attachmentFiles.push(file.raw);
    attachmentFileList.value = fileList;
};

const submitAnnouncement = async () => {
    const formData = new FormData();
    if (newAnnouncement.value.title == ""){
        ElMessage.error("请输入公告标题");
        return;
    }
    if (newAnnouncement.value.deadLine == ""){
        ElMessage.error("请输入公告截止时间")
        return;
    }
    formData.append('title', newAnnouncement.value.title);
    formData.append('deadLine', newAnnouncement.value.deadLine);
    if (newAnnouncement.value.noticeFile) {
        const file = newAnnouncement.value.noticeFile
        const isLt5M = file.size / 1024 / 1024 < 1;
        if (!isLt5M) {
            ElMessage.error('上传公告文件大小不能超过 5MB!');
            return;
        }
        formData.append('file', newAnnouncement.value.noticeFile);
    }
    else{
        ElMessage.error("请上传通知文件");
        return;
    }
    if (newAnnouncement.value.attachmentFiles.length > 0) {
        const flag = true;
        newAnnouncement.value.attachmentFiles.forEach((file, index) => {
            const isLt5M = file.size / 1024 / 1024 < 1;
            if (!isLt5M) {
                ElMessage.error('上传附件大小不能超过 5MB!');
                flag = false;
            }
            formData.append('files', file);
        });
        if (!flag)return;
    }

  try {
        const config = {
            onUploadProgress: (progressEvent) => {
                const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                if (percentCompleted >= 75) {
                    // 设置进度条为75%到99%之间的随机值
                    const randomPercent = Math.floor(Math.random() * (99 - 75 + 1)) + 75;
                    uploadProgress.value = randomPercent;
                } else {
                    uploadProgress.value = percentCompleted;
                }

            }
        };

        await issueNotice(formData, config);
        ElMessage.success('公告发布成功');
        // 刷新公告列表或其他操作
        // 后端返回成功状态，设置进度条为100%
        uploadProgress.value = 100;
        progressStatus.value = 'success';

        getAnnouncements(currentPage.value, pageSize.value);
        console.log("通知已经发布成功了")
  } catch (error) {
    ElMessage.error('公告发布失败');
    progressStatus.value = 'exception';
  }
};


// 删除公告
const deleteSelectedAnnouncements = async () => {
  if (selectedAnnouncements.value.length === 0) {
    ElMessage.warning('请先选择要删除的公告');
    return;
  }

  try {
    await deleteAnnouncementsApi(selectedAnnouncements.value);
    ElMessage.success('选中的公告删除成功');
    getAnnouncements(currentPage.value, pageSize.value);
  } catch (error) {
    ElMessage.error('公告删除失败');
  }
};

// 获取公告列表
const getAnnouncements = async (current, size) => {
  try {
    const res = await fetchAnnouncements(current, size);
    total.value = res.count;
    announcements.value = res.data;
  } catch (error) {
    ElMessage.error('获取公告失败');
  }
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  getAnnouncements(currentPage.value, pageSize.value);
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  getAnnouncements(currentPage.value, pageSize.value);
};

onMounted(() => {
  getAnnouncements(currentPage.value, pageSize.value);
});

const showAttachments = (id, title) => {
  nextTick(() => {
    if (attachmentList.value) {
      attachmentList.value.showAttachments(id, title);
    } else {
      ElMessage.error('附件列表组件未加载完成');
    }
  });
};
const isFileCountPassed = (fileCount) =>{
    return !(fileCount > 0);
}

// 展示公告详情
const showDetails = (row) => {
    selectedAnnouncement.value = row;
    dialogVisible.value = true;
};

const handleClose = () => {
    dialogVisible.value = false;
};


</script>


<style scoped lang="scss">
    .box {
        height: 100%;
        padding: 15px;
        position: relative;
        .el-pagination {
            position: absolute;
            bottom: 25px;
        }
    }
    .top {
        display: flex;
        width: 100%;
        height: 50px;
        line-height: 50px;
        align-items: center;
        margin-bottom: 15px;
    }
    .my-header {
        display: flex;
        height: 50px;
        line-height: 50px;
    .titleClass {
        font-size: 25px;
        }
    }
    .details {
        h3 {
        margin-top: 0;
        }
        p {
            margin: 5px 0;
        }
    }

</style>